package org.thirdHero.db.template;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GenerateController {

    private static String demoName = "SysRedPackage";
    private static String targetPath = "/Volumes/code 1/fresh-service/travel-admin-api/src/main/java/org/thirdHero/admin/web";
    private static String templateDirectory = "/Volumes/code 1/fresh-service/travel-db/src/main/resources/template/";
    private static String packageName = "org.thirdHero.admin.web";
    //需要进行查询的参数列表
    private static List<String> params = new ArrayList<String>();
    //需要动态查询的属性列表
    private static List<String> properties = new ArrayList<>();

    static {
        //属性要大写
        properties.add("Name");
        properties.add("CategoryId");
        properties.add("Desc");
    }



    public static void main(String[] args) throws IOException {
        // 参数值
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("type", "String");
        map.put("demoName", demoName);
        map.put("packageName",packageName);
        map.put("properties",properties);

        // 模板目录
        // 模板名称
        String templateFile = "Controller.java.btl";
        // 模板生成后存放目录
        // 模板生成后新文件名
        String fileName = demoName+"Controller.java";
        // 创建文件夹
        new File(targetPath).mkdirs();
        File nFile = new File(targetPath +"/"+ fileName);
        if (nFile.exists()) {
            throw new RuntimeException("File \'"+fileName+"\' already exists");
        }

        // 生成目标文件
        Writer writer = null;
        try {
            writer = new FileWriter(nFile);

            Template template = getConfiguration(templateDirectory).getTemplate(templateFile, "UTF-8");
            template.process(map, writer);

        } catch (TemplateException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            writer.close();
        }
    }

    private static Configuration getConfiguration(String templateDirectory) {

        Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
        try {
            configuration.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX);
            configuration.setDirectoryForTemplateLoading(new File(templateDirectory));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return configuration;
    }

}
